#include <windows.h>

#include "resource.h"

BOOL CALLBACK DlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char * lpCmdLine, int cmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	HWND hDialog = CreateDialog (hInstance, MAKEINTRESOURCE (IDD_MAIN), 0, DlgProc);

	if (!hDialog)
    {
        wchar_t buf [100];
        wsprintf (buf, L"Error x%x", GetLastError ());
        MessageBox (0, buf, L"CreateDialog", MB_ICONEXCLAMATION | MB_OK);
        return 1;
    }

	ShowWindow(hDialog, SW_SHOW); 

	MSG msg;

	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return (int) msg.wParam;

}

BOOL OnCommand(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	int wmId    = LOWORD(wParam);
	int wmEvent = HIWORD(wParam);

	if (LOWORD(wParam) == ID_FIND || LOWORD(wParam) == ID_EXIT)
	{
		DestroyWindow (hwndDlg);
	}
	return TRUE;
}

BOOL CALLBACK DlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	HWND hwndOwner; 
	RECT rc, rcDlg, rcOwner; 

	switch (message)
	{
	case WM_INITDIALOG:
		// Get the owner window and dialog box rectangles. 

		if ((hwndOwner = GetParent(hwndDlg)) == NULL) 
		{
			hwndOwner = GetDesktopWindow(); 
		}

		GetWindowRect(hwndOwner, &rcOwner); 
		GetWindowRect(hwndDlg, &rcDlg); 
		CopyRect(&rc, &rcOwner); 

		// Offset the owner and dialog box rectangles so that right and bottom 
		// values represent the width and height, and then offset the owner again 
		// to discard space taken up by the dialog box. 

		OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); 
		OffsetRect(&rc, -rc.left, -rc.top); 
		OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); 

		// The new position is the sum of half the remaining space and the owner's 
		// original position. 

		SetWindowPos(hwndDlg, 
			HWND_TOP, 
			rcOwner.left + (rc.right / 2), 
			rcOwner.top + (rc.bottom / 2), 
			0, 0,          // Ignores size arguments. 
			SWP_NOSIZE);

		

		return TRUE;

	case WM_CTLCOLORDLG:
		{
		 HBRUSH g_hbrBackground = CreateSolidBrush(0xE4CAF5);
		 return (LONG)g_hbrBackground;
		}

    case WM_COMMAND:
        return OnCommand(hwndDlg, message, wParam, lParam);
    
	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	default: 
		return FALSE; 
    }
	
	return FALSE;
}

